/**
 * Created by lichong on 2/26/2018.
 */

import {message} from 'antd';
import 'whatwg-fetch';
import StorageUtils from 'utils/StorageUtils'


const catalogServiceUrl = 'http://localhost:8080/api/catalog-service';
const cartServiceUrl = 'http://localhost:8080/api/cart-service';
const userServiceUrl = 'http://localhost:8080/api/user-service'
const orderServiceUrl = 'http://localhost:8080/api/order-service';
const paymentServiceUrl = 'http://localhost:8080/api/payment-service';
const searchServiceUrl = 'http://localhost:8080/api/search-service';
const reviewServiceUrl = 'http://localhost:8080/api/review-service'
// const catalogServiceUrl = 'http://localhost:8801';
// const cartServiceUrl = 'http://localhost:8804';
// const userServiceUrl = 'http://localhost:8803'
// const orderServiceUrl = 'http://localhost:8802';
// const paymentServiceUrl = 'http://localhost:8806';
// const searchServiceUrl = 'http://localhost:8807';
// const reviewServiceUrl = 'http://localhost:8805'

const HttpUtils = {

    productServiceUrl: catalogServiceUrl,
    productGroupServiceUrl: catalogServiceUrl,
    floorServiceUrl: catalogServiceUrl,
    categoryServiceUrl: catalogServiceUrl,
    cartServiceUrl: cartServiceUrl,
    userServiceUrl: userServiceUrl,
    orderServiceUrl: orderServiceUrl,
    paymentServiceUrl: paymentServiceUrl,
    searchServiceUrl: searchServiceUrl,
    commentServiceUrl: reviewServiceUrl,

    get(url, options, callback) {
        let parameterizedUrl = this.buildUrl(url, options.params);
        let request = Object.assign({
            method: 'GET',
            headers: {
            },
            credentials: 'include'
        } , options)
        let token = StorageUtils.getToken()
        if(token){
            request.headers.Authorization = 'Bearer ' + token
        }
        fetch(parameterizedUrl, request)
            .then((resp) => {
                if(resp.status >= 200 && resp.status < 300){
                    return resp.json()
                }
                let error = new Error(resp.statusText)
                error.response = resp.json()
                error.customError = true
                throw error
            })
            .then((resp) => {
                callback.success(resp);
            })
            .catch((error) => {
                if(!error.customError){
                    throw error
                }
                let promise = error.response
                promise.then(function(value){
                    if(callback.error){
                        callback.error(value)
                    } else {
                        message.error(value.error_message)
                    }
                })
            })
    },

    buildUrl(url, params) {
        if (typeof(url) == 'undefined' || url == null || url == '') {
            return '';
        }
        if (typeof(params) == 'undefined' || params == null || typeof(params) != 'object') {
            return url;
        }
        url += (url.indexOf("?") != -1) ? "" : "?";
        for (var k in params) {
            url += ((url.indexOf("=") != -1) ? "&" : "") + k + "=" + encodeURI(params[k]);
        }
        return url;
    },

    getQueryString(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return decodeURI(r[2]);
        return null;
    },

    changeUrlParam(url, arg, val){
        var pattern = arg+'=([^&]*)';
        var replaceText = arg+'='+val;
        return url.match(pattern) ? url.replace(eval('/('+ arg+'=)([^&]*)/gi'), replaceText) : (url.match('[\?]') ? url+'&'+replaceText : url+'?'+replaceText);
    },

    /**
     * credentials: 'include'   在执行跨域传递cookie时需要这个选项
     * @param url
     * @param data
     * @param callback
     */
    post(url, data, callback , options) {
        let request = Object.assign({
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            body: data,
            credentials: 'include'
        } , options)
        let token = StorageUtils.getToken()
        if(token){
            request.headers.Authorization = 'Bearer ' + token
        }
        fetch(url, request)
            .then((resp) => {
                if(resp.status >= 200 && resp.status < 300){
                    return resp.json()
                }
                let error = new Error(resp.statusText)
                error.response = resp.json()
                error.customError = true
                throw error
            })
            .then((resp) => {
                callback.success(resp);
            })
            .catch((error) => {
                if(!error.customError){
                    throw error
                }
                let promise = error.response
                promise.then(function(value){
                    if(callback.error){
                        callback.error(value)
                    } else {
                        message.error(value.error_message)
                    }
                })
            })
    },

    /*  search */

    hotSearch(callback){
        this.get(this.searchServiceUrl + '/hotSearch' , {} , callback)
    },

    searchTips(options , callback){
        this.get(this.searchServiceUrl + "/searchTips" , options , callback)
    },

    searchProducts(searchUrl , callback){
        this.get(this.searchServiceUrl + "/search" + searchUrl , {} , callback)
    },

    moreLikeThis(prodId , callback){
        this.get(this.searchServiceUrl + "/mlt" , {params : {prodId}} , callback)
    },

    /* catalog service */
    getNavigator(params , callback) {
        this.get(this.categoryServiceUrl + "/navigator" , params , callback)
    },

    getCrumbs(options, callback) {
        this.get(this.categoryServiceUrl + '/crumbs', options, callback);
    },

    getFloor(options, callback) {
        this.get(this.productServiceUrl + '/floor', {}, callback);
    },

    getProductInfo(prodId, callback) {
        this.get(this.productServiceUrl + '/product/' + prodId, {}, callback);
    },

    getProductImages(options , callback){
        this.get(this.productServiceUrl + '/images' , options , callback)
    },

    getProductDesc(options, callback) {
        this.get(this.productGroupServiceUrl + '/productGroup/detail', options, callback);
    },

    getProductAttributes(options, callback) {
        this.get(this.productServiceUrl + '/attributes', options, callback);
    },

    /* cart service */
    getMyCart(options, callback) {
        this.get(this.cartServiceUrl + '/mycart', options, callback);
    },

    addItem(cartitem , callback){
        this.post(this.cartServiceUrl + '/addItem' , JSON.stringify(cartitem) , callback);
    },

    removeItem(prodId , callback){
        let data = new URLSearchParams();
        data.append("id" , prodId);
        data.append("prodId" , prodId);
        let headers = {
            'Accept': 'application/json',
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        }
        this.post(this.cartServiceUrl + '/removeItem' , data, callback , {headers})
    },

    selectItem(prodId , callback){
        let data = new URLSearchParams();
        data.append("prodId" , prodId);
        let headers = {
            'Accept': 'application/json',
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        }
        this.post(this.cartServiceUrl + '/selectItem' , data, callback , {headers})
    },

    cancelItem(prodId , callback){
        let data = new URLSearchParams();
        data.append("prodId" , prodId);
        let headers = {
            'Accept': 'application/json',
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        }
        this.post(this.cartServiceUrl + '/cancelItem' , data, callback , {headers})
    },

    selectAllItems(callback){
        let data = new URLSearchParams();
        let headers = {
            'Accept': 'application/json',
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        }
        this.post(this.cartServiceUrl + '/selectAllItems' , data, callback , {headers})
    },

    cancelAllItems(callback){
        let data = new URLSearchParams();
        let headers = {
            'Accept': 'application/json',
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        }
        this.post(this.cartServiceUrl + '/cancelAllItems' , data, callback , {headers})
    },

    changeQuantity(prodId , quantity, callback){
        let data = new URLSearchParams();
        data.append("prodId" , prodId);
        data.append("quantity" , quantity);
        let headers = {
            'Accept': 'application/json',
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        }
        this.post(this.cartServiceUrl + '/changeQuantity' , data, callback , {headers})
    },

    clearCart(options , callback){
        this.post(this.cartServiceUrl + '/clear' , options,  callback)
    },

    getMiniCart(options, callback) {
        this.get(this.cartServiceUrl + '/minicart', options, callback);
    },

    /* user service */

    requestVCode(mobile , callback){
        let data = new URLSearchParams();
        data.append("mobile" , mobile);
        let headers = {
            'Accept': 'application/json',
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        }
        this.post(this.userServiceUrl + '/requestVCode' , data, callback , {headers})
    },

    createAddress(address , callback){
        this.post(this.userServiceUrl + '/address', JSON.stringify(address), callback);
    },

    getMyAddress(options, callback) {
        this.get(this.userServiceUrl + '/myAddresses', options, callback);
    },

    deleteMyAddress(options, callback) {
        this.get(this.userServiceUrl + '/address/remove?id=' + options.id, options, callback);
    },

    login(user, callback) {
        this.post(this.userServiceUrl + '/login', JSON.stringify(user), callback);
    },

    logout(callback){
        this.get(this.userServiceUrl + '/logout' , {}, callback);
    },

    register(user , callback) {
        this.post(this.userServiceUrl + '/register', JSON.stringify(user), callback);
    },

    getSku(options, callback) {
        this.get(this.productServiceUrl + '/sku/' + options.id, options, callback);
    },

    addToFavor(prodId, callback){
        let data = new URLSearchParams();
        data.append("prodId" , prodId);
        let headers = {
            'Accept': 'application/json',
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        }
        this.post(this.userServiceUrl + '/favorites' , data, callback , {headers})
    },

    /* order service */
    checkout(data, callback) {
        this.post(this.orderServiceUrl + '/checkout', JSON.stringify(data), callback)
    },

    createOrder(order , callback){
        this.post(this.orderServiceUrl + '/order', JSON.stringify(order), callback)
    },

    getOrder(options , callback){
        this.get(this.orderServiceUrl + "/myorders/" + options.id , options , callback)
    },

    listUnCommentedItems(orderId , callback){
        this.get(this.orderServiceUrl + '/unCommentedItems' , {params : {orderId}} ,callback)
    },

    listMyOrders(callback){
        this.get(this.orderServiceUrl + '/myorders' , {} ,callback)
    },

    cancelOrder(orderId , callback){
        let data = new URLSearchParams();
        data.append("orderId" , orderId);
        let headers = {
            'Accept': 'application/json',
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        }
        this.post(this.userServiceUrl + '/cancelOrder' , data, callback , {headers})
    },

    /* payment service */
    getPayment(options , callback){
        this.get(this.paymentServiceUrl + '/pay' , options , callback)
    },

    getQrImage(options , callback){
        this.get(this.paymentServiceUrl + "/getQrImage" , options , callback)
    },

    checkPaymentStatus(orderId , callback){
        this.get(this.paymentServiceUrl + '/checkStatus' , {params : {orderId}} , callback)
    },

    /* comment service */
    createComment(comment , callback){
        this.post(this.commentServiceUrl + '/comment' , JSON.stringify(comment) , callback)
    },

    listSurveys(orderId , callback) {
        this.get(this.commentServiceUrl + '/orderItemSurveys' , {params : {orderId}} , callback)
    },

    listComments(pgId , callback){
        this.get(this.commentServiceUrl + '/comments' , {params : {pgId}} , callback)
    }

}

export default HttpUtils;